﻿using Common.Helper;
using IRepository;
using IService.Entity;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Entity
{
    public class BRoleService:IBRoleService
    {
        readonly ILogger<BRoleService> logger;
        readonly IBaseRepository baseRepository;
        public BRoleService(ILogger<BRoleService> _logger, IBaseRepository _baseRepository)
        {
            logger = _logger;
            baseRepository = _baseRepository;
        }

        #region Get

        /// <summary>
        /// 查询所有角色（分页）
        /// </summary>
        /// <param name="offset">页数</param>
        /// <param name="limit">每页数</param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetAllToPage(int offset = 1, int limit = 15)
        {
            try
            {
                PageInfoModel<BRole> pageList = await baseRepository.QueryPage<BRole>(offset, limit, "ID");
                PageInfoModel<object> list = new PageInfoModel<object>();
                list.DataCount = pageList.DataCount;
                list.PageSize = pageList.PageSize;
                list.PageCount = pageList.PageCount;
                list.Page = pageList.Page;
                list.Data = new List<object>();
                foreach (var item in pageList.Data)
                {
                    List<BRoleMenu> roleMenus = baseRepository.Query<BRoleMenu>(n => n.RoleID == item.ID).Result;
                    List<BMenu> menus = new List<BMenu>();
                    foreach (var i in roleMenus)
                    {
                        BMenu menu = baseRepository.Query<BMenu>(n => n.ID == i.MenuID).Result.FirstOrDefault();
                        menus.Add(menu);
                    }
                    list.Data.Add(new
                    {
                        id = item.ID,
                        roleName=item.RoleName,
                        roleDesc=item.RoleDesc,
                        menus= menus,
                        createdAt = item.CreatedAt,
                        updatedAt = item.UpdatedAt
                    });
                };

                string result = JsonConvert.SerializeObject(list);

                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询所有角色
        /// </summary>
        /// <param name="bRole"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<BRole>>> GetAll()
        {
            try
            {
                List<BRole> result = await baseRepository.Query<BRole>();
                //string FunName = MethodBase.GetCurrentMethod().DeclaringType.Name;//获取当前方法名
                //FunName = FunName.Substring(FunName.IndexOf('<')+1,FunName.LastIndexOf('>')-1);
                //LogLock.OutLogFile("UserService_GetAll", "", JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BRole>>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BRole>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 根据条件表达式查询数据列表
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>数据列表</returns>
        public async Task<MessageModel<List<BRole>>> GetByExpression<BRole>(Expression<Func<BRole, bool>> whereExpression)
        {
            try
            {
                List<BRole> result = await baseRepository.Query(whereExpression);
                //LogLock.OutLogFile("GetByExpression", JsonConvert.SerializeObject(whereExpression), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BRole>>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BRole>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询角色按ID
        /// </summary>
        /// <param name="bRole"></param>
        /// <returns></returns>
        public async Task<MessageModel<BRole>> GetById(int id)
        {
            try
            {
                BRole result = await baseRepository.Query<BRole>(id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<BRole>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<BRole>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="bRole"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Post(BRole bUser)
        {
            try
            {
                //获取角色ID
                bUser.ID = await baseRepository.Add(bUser);
                //LogLock.OutLogFile("Post", JsonConvert.SerializeObject(bRole), JsonConvert.SerializeObject(bRole), true);//存入日志
                return new MessageModel<string>()
                {
                    Code = 200,
                    Data = bUser.ID.ObjToString(),
                    Message = "添加成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Put
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="bRole"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Put(BRole bUser)
        {
            try
            {
                bool flag = await baseRepository.Update(bUser);
                if (flag)
                {
                    return new MessageModel<string>()
                    {
                        Code = 200,
                        Data = bUser.ID.ObjToString(),
                        Message = "修改成功",
                        Success = true
                    };
                }
                return new MessageModel<string>()
                {
                    Data = null,
                    Message = "修改失败",
                    Success = false
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="bRole"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DelById(int id)
        {
            try
            {
                bool flag = await baseRepository.DeleteById<BRole>(id);
                //LogLock.OutLogFile("DelById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(flag), true);//存入日志
                return new MessageModel<bool>()
                {
                    Code = 200,
                    Data = flag,
                    Message = "删除成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<bool>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

    }
}
